#include "stdafx.h"
#include "AlarmEventHandler.h"
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>

namespace Network
{
	AlarmEventHandler::AlarmEventHandler(const INET_Addr& ipAddress)
	{
		//create SOCK_Acceptor listener of the ip address
		listener = new SOCK_Acceptor(ipAddress);
		alarms.clear();
	}

	AlarmEvent readAlarm(unsigned char* data) 
	{
		AlarmEvent evt;
		char *s;
		char pr = data[0];
		int n = data[1];

		s = (char*)malloc(n);

		int idx = 0;
		while (idx < n) {
			s[idx] = data[idx+2];
			idx++;
		}		
		evt.priority = pr;
		evt.text = std::string(s);
		free(s);
		return evt;
	}

	void AlarmEventHandler::handle(unsigned char* data)
	{
		AlarmEvent evt = AlarmEvent();

		if (0 != deserializeAlarmEvent((char*)data, &evt)) {
			fprintf(stdout, "Error in deserialization of AlarmEvent!");
		}

		time_t timestamp;
		time(&(timestamp));
		AlarmEventItem alarmEventItem(evt, timestamp);
		alarms.push_back(alarmEventItem);

		// sort the vector according to priority and pop off the back if it is larger than 10
		std::sort(alarms.begin(), alarms.end(), AlarmEventItemPriorityComparer());
		while (alarms.size() > 10) {
			alarms.pop_back();
		}

		cout << "Alarm count: " << alarms.size() << "\n";
		for(u_int i = 0; i < alarms.size(); i++){
			char buffer[26];
			ctime_s(buffer, 26, &(alarms.at(i).timestamp));
			cout << "Alarm => Priority = " << alarms.at(i).event.priority << " time = " << buffer << " text = " << alarms.at(i).event.text << "\n";
		}
	}
}